<?php


class RefreshClient {
	const HOST = "great-config-for-php";

	const CLEAR_URL = "/clear_great_config.php";
	const RELOAD_URL = "/reload_great_config.php";

	const PORT = "8411";

	public static function clear($host) {
		return self::_request($host, self::CLEAR_URL);
	}

	public static function reload($host) {
		return self::_request($host, self::RELOAD_URL);
	}

	protected static function _request($host, $url) {
		$errno = 0;
		$errstr = '';
		$fp = fsockopen($host, self::PORT, $errno, $errstr, 120);

		if($errno != 0) {
			throw new Exception ("Connect to $host failed: $errstr");
		}
		if(!$fp) {
			throw new Exception ("Connect to $host failed!");	
		}

		$out = "GET $url HTTP/1.0 \r\n";
		$out .= "Host: " . self::HOST . "\r\n";
		$out .= "Connection: Close\r\n\r\n";

		fwrite($fp, $out);

		$ret = '';
		while(!feof($fp)) {
			$ret .= fgets($fp, 1024);	
		}
		fclose($fp);
		if(preg_match("/^HTTP\/[\d\.]+\s+(\d+)\s+(.*)/i", $ret, $matches) !== false) {
			if($matches[1] != 200) {
				throw new Exception ("Refresh $host failed: " . $matches[1] . $matches[2]);
			}
			$ret = substr($ret, strpos($ret, "\r\n\r\n") + 4);
		} else {
			throw new Exception ("Refresh $host failed: not http ?!");
		}
		return trim($ret) == "1";
	}
}
